package com.twt.sys.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private final String ROOT_PATH = "/**";
    private List<String> withePathList = new LinkedList<>();

    public List<String> addWithePath(String path) {
        this.withePathList.add(path);
        return this.withePathList;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        log.debug("拦截[{}]",path);
        if (!this.checkPath(path)) {
            return true;
        }
        if (!this.checkLogin(request)) {
            throw new NotLoginException();
        } else {
            return true;
        }
    }

    private boolean checkLogin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) return false;

        String id = session.getId();
        if (LoginContext.INSTANCE.contains(id)) {
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    private boolean checkPath(String path) {
        if (this.withePathList.contains(path)) {
            return false;
        }
        PathMatcher pathMatcher = new AntPathMatcher();
        return pathMatcher.match(ROOT_PATH, path);
    }


    /*public static void main(String[] args) {
        LoginInterceptor loginInterceptor = new LoginInterceptor();
        System.out.println(loginInterceptor.checkPath("/member/listPage"));
        System.out.println(loginInterceptor.checkPath("/member/listPage.do"));
        System.out.println(loginInterceptor.checkPath("/member"));
    }*/
}
